package ldh.im.fxgui.component.message;

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.layout.StackPane;
import ldh.im.fxbase.component.LimitDataListView;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxgui.handle.IMessageEditorHandler;
import ldh.im.fxgui.component.message.bo.WrapImMessage;

import java.util.List;
import java.util.stream.Collectors;

public class MessageLimitListViewHandler extends BaseMessageListViewHandler {

    private LimitDataListView<WrapImMessage> limitDataListView;

    public MessageLimitListViewHandler(IMessageEditorHandler messageEditorService, StackPane dialogRoot) {
        super(messageEditorService, dialogRoot);
        limitDataListView = new LimitDataListView<>(data-> createMessagePane(data));
    }

    @Override
    public Node createMessagePaneNode() {
        return limitDataListView;
    }

    @Override
    public boolean addMessage(ImMessage message) {
        if (imSession != null) {
            if (imSession.isP2p()) {
                if (!imSession.getToUserId().equals(message.getFromUserId())) return false;
            } else {
                if (!imSession.getImGroup().getServerId().equals(message.getGroupCode())) return false;
            }
        }
        limitDataListView.addLast(WrapImMessage.wrap(message));
        return true;
    }

    @Override
    public void addMessage(int index, ImMessage message) {
        if (!this.imSession.getId().equals(message.getSessionId())) return;
        limitDataListView.addLast(WrapImMessage.wrap(message));
    }

    @Override
    public void addMessages(List<ImMessage> messages) {
        if (messages.size() < 1) return;
        List<ImMessage> canMessages = messages.stream().filter(m->imSession.getId().equals(m.getSessionId())).collect(Collectors.toList());
        if (canMessages.size() < 1) return;

        List<WrapImMessage> wrapImMessages = canMessages.stream().map(m->WrapImMessage.wrap(m)).collect(Collectors.toList());
        limitDataListView.addLasts(wrapImMessages);
    }

    @Override
    public void addFrontMessages(List<ImMessage> messages) {
        if (messages.size() < 1) return;
        if (!this.imSession.getId().equals(messages.get(0).getSessionId())) return;

        List<WrapImMessage> wrapImMessages = messages.stream().map(m->WrapImMessage.wrap(m)).collect(Collectors.toList());
        limitDataListView.addFronts(wrapImMessages);
    }

    @Override
    public ObservableList<WrapImMessage> getItems() {
        return limitDataListView.getItems();
    }

}
